<template>
  <div class="table-container" v-loading.fullscreen.lock="fullscreenLoading">
    <el-button style="position: absolute; right: 0" v-print="printObj" type="primary">打印</el-button>
    <div id="printTable" style="position: relative;min-height: 90vh;">
      <h2 style="text-align: center">
        凉山州第一人民医院重症监护室（ICU）ECMO运行记录单
      </h2>
      <div class="basicInformation">
        <div>患者姓名：{{ peopleData.NAME }}</div>
        <div>床号：{{ peopleData.BEDNAME }}</div>
        <div>住院号：{{ peopleData.ADMISSIONNUMBER }}</div>
        <div>ECMO日期：{{ peopleData.INFODATE }}</div>
      </div>
      <table class="complex-table">
        <!-- 第一行表头 -->
        <thead>
          <tr>
            <template v-for="(header, index) in headers" :key="index">
              <th v-if="!header.children" :rowspan="header.rowspan || 1" :colspan="header.colspan || 1">
                {{ header.title }}
              </th>
              <th v-else :colspan="header.children.length">
                {{ header.title }}
              </th>
            </template>
          </tr>

          <!-- 第二行表头 -->
          <tr>
            <template v-for="(header, index) in headers" :key="index">
              <template v-if="header.children">
                <template v-for="(child, childIndex) in header.children" :key="childIndex">
                  <th>
                    {{ child.title }}
                  </th>
                </template>
              </template>
            </template>
          </tr>
          <!-- 第三行表头 -->
          <tr style="font-size: 10px">
            <template v-for="(header, index) in headers" :key="index">
              <template v-if="header.children">
                <template v-for="(child, childIndex) in header.children" :key="childIndex">
                  <th>
                    {{ child.unit }}
                  </th>
                </template>
              </template>
            </template>
          </tr>
        </thead>

        <!-- 表格内容 -->
        <tbody>
          <tr v-for="(item, rowIndex) in tableData" :key="rowIndex">
            <td v-for="(value, key) in item" :key="key">
              <img :src="'data:image/gif;base64,' + value" alt="" width="50px" height="30px"
                v-if="isShow(item, key, value)" />
              <span v-else>{{ value }}</span>
            </td>
          </tr>
        </tbody>
      </table>
      <!-- 审核人区域 - 固定在右下角 -->
      <div class="audit-area">
        <div class="audit-box">
          <div class="audit-label">审核人：</div>
          <div class="audit-signature"><img :src="imgsrc" alt="" class="signature-image" /></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { getEcmoReport } from "../api/book.js";
const headers = [
  {
    title: "时间",
    key: "time",
    rowspan: 3,
  },
  {
    title: "ECMO运行参数",
    key: "params",
    children: [
      { title: "流量", key: "flow", unit: "L/min" },
      { title: "离心泵转速", key: "waterTemp", unit: "" },
      { title: "实际水温", key: "gasFlow", unit: "℃" },
      { title: "FiO₂", key: "analTemp", unit: "%" },
      { title: "气流量", key: "analTemp", unit: "L/min" },
    ],
  },
  {
    title: "温度",
    key: "temperature",
    children: [
      { title: "鼻咽/腋温", key: "flow", unit: "℃" },
      { title: "肛温", key: "gasFlow", unit: "℃" },
    ],
  },
  {
    title: "生命体征",
    key: "vitalSigns",
    children: [
      { title: "HR", key: "hr", unit: "次/分" },
      { title: "SPO₂", key: "abp", unit: "%" },
      { title: "ABP", key: "rd", unit: "mmHg" },
      { title: "MBP", key: "rd", unit: "mmHg" },
      { title: "RR", key: "rd", unit: "次/分" },
    ],
  },
  {
    title: "血气分析",
    key: "bloodGas",
    children: [
      { title: "PH", key: "pco", unit: "" },
      { title: "PCO₂", key: "po", unit: "mmHg" },
      { title: "PO₂", key: "be", unit: "mmHg" },
      { title: "BE", key: "so", unit: "mmol/L" },
      { title: "HCO₃", key: "na", unit: "mmol/L" },
      { title: "Glu", key: "na", unit: "mmol/L" },
      { title: "SO₂", key: "na", unit: "%" },
      { title: "Na⁺", key: "na", unit: "mmol/L" },
      { title: "K²⁺", key: "na", unit: "mmol/L" },
      { title: "iCa²⁺", key: "na", unit: "mmol/L" },
      { title: "Hct", key: "na", unit: "%PCV" },
      { title: "Hb", key: "na", unit: "g/dL" },
      { title: "Lac", key: "na", unit: "mmol/L" },
    ],
  },
  {
    title: "抗凝及监测",
    key: "aa",
    children: [
      { title: "肝素(负荷量)", key: "flow", unit: "" },
      { title: "肝素(维持量)", key: "gasFlow", unit: "" },
      { title: "APTT", key: "gasFlow", unit: "g" },
      { title: "ACT", key: "gasFlow", unit: "g" },
    ],
  },
  {
    title: "呼吸机支持",
    key: "bb",
    children: [
      { title: "模式", key: "gasFlow", unit: "" },
      { title: "F", key: "gasFlow", unit: "次/分" },
      { title: "FiO₂", key: "gasFlow", unit: "%" },
    ],
  },
  {
    title: "肢体远端血供",
    key: "cc",
    rowspan: 3,
  },
  {
    title: "ECMO运行",
    key: "dd",
    rowspan: 3,
  },
  {
    title: "其他",
    key: "other",
    rowspan: 3,
  },
  {
    title: "签名",
    key: "signature",
    rowspan: 3,
  },
];
const imgsrc = ref("");
const tableData = ref([]);
const peopleData = ref({});
const docId = ref("");
const isShow = (item, key, value) => {
  return (
    value &&
    key ===
    Object.keys(item)
      .sort((a, b) => parseInt(a) - parseInt(b))
      .pop()
  );
};
const printObj = {
  id: "printTable",
  preview: false,
  previewTitle: "打印预览",
  popTitle: "good print",
  minW: "100%",
  maxW: "100%",
  extraHead:
    '<meta http-equiv="Content-Language"content="zh-cn"/><style>@media print { @page { size: landscape; } .print-title { position: running(header); text-align: center; font-size: 22px; font-weight: 600; padding: 10px 0; margin: 0; } @page { @top-center { content: element(header); } } }</style>',
  beforeOpenCallback(vue) {
    console.log("打开之前");
  },
  openCallback(vue) {
    console.log("执行了打印");
  },
  closeCallback(vue) {
    console.log("关闭了打印工具");
  },
};
const fullscreenLoading = ref(false);
// 获取图片
const getImg = async (url) => {
  try {
    if (!url) {
      console.error('传入的图片数据为空');
      return { success: false, message: '图片数据为空' };
    }

    // 修复语法错误：应该是 state.imgsrc 而不是 imgsrc.value
    imgsrc.value = `data:image/gif;base64,${url}`;
    // console.log('图片已设置成功');
    // createAndUploadPDF()
    // return { success: true, message: '图片设置成功' };
  } catch (error) {
    console.error('设置图片时出错:', error);
    ElMessage.error('失败:');
    return { success: false, message: '设置图片失败' };
  }
};
// 获取数据
onMounted(() => {
  const route = useRoute(); // 访问查询参数
  window.getImg = getImg;
  if (route.query.docId) {
    docId.value = route.query.docId;
    fullscreenLoading.value = true;
    getEcmoReport(docId.value)
      .then((data) => {
        peopleData.value = data.patientInfo[0];
        imgsrc = data.patientInfo[0].signPic;
        tableData.value = data.reportList;
        fullscreenLoading.value = false;
      })
      .catch((error) => {
        fullscreenLoading.value = false;
      });
  }
});
defineExpose({
  printObj,
});
</script>

<style scoped>
.table-container {
  width: 100%;
  height: 100%;
  position: relative;
}

.basicInformation {
  display: flex;
  justify-content: space-between;
}

.complex-table {
  border-collapse: collapse;
  margin: 10px 0;
  font-size: 14px;
}

.complex-table th,
.complex-table td {
  border: 1px solid #333;
  padding: 6px;
  text-align: center;
}

/* 审核人区域样式 - 固定在右下角 */
.audit-area {
  position: absolute;
  bottom: 10px;
  right: 20px;
  z-index: 10;
}

.audit-box {
  /* border: 2px solid #ff0000; */
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  min-width: 120px;
  text-align: center;
  display: flex;
  /* flex-direction: column; */
  align-items: center;
}

.audit-label {
  font-weight: bold;
  margin-bottom: 5px;
  font-size: 18px;
}

/* 打印样式 */
@media print {
  body {
    margin: 0;
    padding: 0;
    width: 100vw;
  }

  #printTable {
    width: 100% !important;
    max-width: 100% !important;
    transform-origin: 0 0;
  }

  .complex-table {
    border-right: 2px solid #333;
  }

  .h2 {
    width: 100%;
  }

  td {
    font-size: 9pt;
  }

  /* 打印时也固定在右下角 */
  .audit-area {
    position: absolute;
    bottom: 20px;
    right: 20px;
    z-index: 10;
  }

  .audit-box {
    /* border: 2px solid #ff0000; */
    padding: 10px;
    background-color: #fff;
    border-radius: 4px;
    min-width: 120px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  /* 打印时的签名图片样式 */
  .signature-image {
    max-width: 100px;
    max-height: 50px;
    width: auto;
    height: auto;
    object-fit: contain;
  }
}
</style>
